<?php
/**
 * 管理权限体系
 */
namespace Plu\Library\Services\Permission;

use Plu\Library\Services\ServiceBase,
    Plu\Library\Services\Utility\UrlService;

/**
 * in config.php
 * permission => array(
 *   'server' => '', //auth server,
 * )
 */
class PermissionService extends ServiceBase {
    private $_config;

    private $_userid;

    const COOKIE_USERNAME = "p1u_openid";

    public function __construct() {
        $config = $this->config['permission'];
        if (empty($config)) {
            return;
        }

        //需要配置服务器才可以
        if (empty($config['server'])) {
            return;
        }

        $this->_config = $config->toArray();

        $this->authService = $this->grpc->service("go.micro.srv.auth");
    }

    public function login() {
        $authServerUrl = $this->_config['server'];
        //get current url
        $currentUrl = UrlService::getUrl();

        if (!empty($currentUrl)) {
            $authServerUrl = $authServerUrl . "/signin?referer=" . urlencode($currentUrl);
        }

        $this->response->redirect($authServerUrl);
        $this->response->send();
        exit;
    }

    public function checkLogin() {
        $this->cookies->useEncryption(false);
        $userId = $this->cookies->get(self::COOKIE_USERNAME)->getValue();

        if (empty($userId)) {
            return false;
        } else {
            $this->_userid = $userId;
        }
        return true;
    }

    public function getUserId() {
        return $this->_userid;
    }

    public function setUserId($userId) {
        $this->_userid = $userId;
    }

    public function checkPermission($functionId) {
        if (!$this->_userid) {
            return false;
        }

        return $this->authService->Authentication($this->_userid, $functionId)->getPass();
    }

    public function checkPermissions($functionIds) {
        if (!$this->_userid) {
            return false;
        }

        $reply = $this->authService->AuthenticationMulti($this->_userid, $functionIds);

        return [
            'result' => iterator_to_array($reply->getResult())
        ];
    }

    public function logout() {

    }
}
